package com.k8.common.util;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class DoublyLinkedList<T> {

    public void clear() {
        Node<T> t = head;
        while (t != null) {
            Node<T> tNode = t.next;
            t.prev = null;
            t.next = null;
            t = tNode;
        }
        head = null;
        tail = null;
    }

    public static class Node<T> {
        private T value;
        public Node<T> prev;
        public Node<T> next;

        public T getValue() {
            return value;
        }

        Node(T value) {
            this.value = value;
        }
    }

    private Node<T> head;
    private Node<T> tail;
    private int size;

    public DoublyLinkedList() {
        head = null;
        tail = null;
        size = 0;
    }


    public Node<T> addLast(T value) {
        Node<T> newNode = new Node<>(value);
        if (tail == null) {
            head = newNode;
        } else {
            tail.next = newNode;
            newNode.prev = tail;
        }
        tail = newNode;
        size++;
        return newNode;
    }


    public Node<T> addFirst(T value) {
        Node<T> newNode = new Node<>(value);
        if (head == null) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.next = head;
            head.prev = newNode;
            head = newNode;
        }
        size++;
        return newNode;
    }

    public Node<T> poll() {
        if (head == null) return null;
        else if (head == tail) {
            Node<T> tNode = head;
            head = null;
            tail = null;
            size = 0;
            return tNode;
        } else {
            Node<T> tNode = head;
            head = head.next;
            size--;
            return tNode;
        }
    }

    public void remove(Node<T> node) {
        if (node == null) return;
        if (node.prev != null) {
            node.prev.next = node.next;
        } else {
            head = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        } else {
            tail = node.prev;
        }
        size--;
    }


    public void printList() {
        Node<T> current = head;
        while (current != null) {
            System.out.print(current.value + " ");
            current = current.next;
        }
        System.out.println();
    }


    public Node<T> getNodeAt(int index) {
        if (index < 0 || index >= size) return null;
        Node<T> current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current;
    }

    public int size() {
        return size;
    }
}
